import { Injectable } from '@angular/core';


import * as crypto from 'crypto-js';

@Injectable({
  providedIn: 'root'
})
export class DataStorageService {

  private AESKey: string = 'cczeng';

  constructor() { }


  /**
   * 使用AES加密数据写入 localStorage
   *
   * @param {string} item
   * @param {string} value
   * @memberof DataStorageService
   */
  setLocal(item: string, value: string) {
    // 加密
    const ciphertext = this.encryption(value);
    console.log(`${value} - ${ciphertext}`);
    // 写入
    localStorage.setItem(item, ciphertext);
  }


  /**
   * 读取本地 localStroage, 并解密AES,如果没有读取到该值,则返回null
   *
   * @param {string} item
   * @returns {string}
   * @memberof DataStorageService
   */
  getLocal(item: string): string {
    // 解密
    const itemValue = localStorage.getItem(item);
    if (itemValue && itemValue !== null) {
      const bytes = this.decryption(itemValue);     // !. 非空断言符
      console.log(`${item} - ${bytes}`);
      return bytes;
    }
    return null;
  }


  /**
   * AES加密方法,传入一个字符串进行AES加密
   *
   * @param {*} value
   * @returns {string}
   * @memberof DataStorageService
   */
  encryption(value): string {
    const ciphertext = crypto.AES.encrypt(value, this.AESKey);
    // console.log(`[加密数据] ${value} - ${ciphertext}`);
    return ciphertext.toString();
  }


  /**
   * AES解密方法,传入一个被AES加密过的字符串进行解密
   *
   * @param {*} value
   * @returns {string}
   * @memberof DataStorageService
   */
  decryption(value): string {
    const bytes = crypto.AES.decrypt(value!.toString(), this.AESKey);
    // console.log(`[解密数据] ${value} - ${bytes}`);
    return bytes.toString(crypto.enc.Utf8);
  }
}
